package com.ibox.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.util.SparseArray;
import android.view.View;

import com.ibox.BaseApplication;

import me.yokeyword.fragmentation.SupportActivity;

/**
 * Project IBox
 * Created by Amos
 * Created on 2017-09-25
 * Desc
 */

public abstract class BaseActivity extends SupportActivity {

    protected Activity mContext;
    private SparseArray<View> mViews;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        mContext = this;
        mViews = new SparseArray<>();
        BaseApplication.getInstance().addActivity(this);
        initView();
        initData();
        configViews();
    }


    /**
     * 通过ViewId获取控件
     *
     * @param id
     * @param <V>
     * @return
     */
    public <V extends View> V findView(@IdRes int id) {
        View view = mViews.get(id);
        if (view == null) {
            view = super.findViewById(id);
            mViews.put(id, view);
        }
        return (V) view;
    }

    /**
     * 封装根据View的id获取view，减少类型强转操作
     *
     * @param id
     * @param <V>
     * @return
     */
    public <V extends View> V getViewById(@IdRes int id) {
        View view = mViews.get(id);
        if (view == null) {
            view = super.findViewById(id);
            mViews.put(id, view);
        }
        return (V) view;
    }

    /**
     * 设置布局
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 进行View的初始化
     */
    public abstract void initView();

    /**
     * 初始化事件和数据
     */
    public abstract void initData();

    /**
     * 对各种控件进行设置、适配、填充数据
     */
    public abstract void configViews();

    protected void gone(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    protected void visible(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }

    }

    protected boolean isVisible(View view) {
        return view.getVisibility() == View.VISIBLE;
    }
}
